
// import type HandsontableCore from 'handsontable';
import type { CellProperties } from 'handsontable';
import type Core from 'handsontable';
import { getCurrentInstance } from "vue";
import { zhCN, registerLanguageDictionary } from "handsontable/i18n";
import { registerAllModules } from 'handsontable/registry';
import Handsontable from 'handsontable';
import cloneDeep from 'lodash/cloneDeep';

import type { HotElementInitSetting } from './interfaces';
import { defaultTableConfig } from './constants';


export class Pagination {
    current: number;
    pageSize: number;
    total: number;
    constructor(current: number = 1, pageSize: number = 10, total: number = 180) {
        this.current = current;
        this.pageSize = pageSize;
        this.total = total;
    }
}

export class Operation {
    enableEdit: boolean;
    enableDelete: boolean;
    enableView: boolean;
    enableAdd: boolean;
    constructor(enableEdit: boolean = true, enableDelete: boolean = true, enableView: boolean = true, enableAdd: boolean = true) {
        this.enableEdit = enableEdit;
        this.enableDelete = enableDelete;
        this.enableView = enableView;
        this.enableAdd = enableAdd;
    }
    // 处理详情点击
    handleDetail(instance: Core, row: number) {
        console.log('查看详情:', instance.getSourceDataAtRow(row));
        // 实现你的详情查看逻辑
    };

    // 处理删除点击
    chandleDelete(instance: Core, row: number) {
        // 实现你的删除逻辑
        // console.log(instance.getSourceDataAtRow(row));
        // console.log(instance)
        console.log("hotTableRef.value.hotInstance", instance.getSourceDataAtRow(row));
    };

    // 处理编辑点击
    chandleEdit(instance: Core, row: number) {
        // 实现你的删除逻辑
        // console.log(instance.getSourceDataAtRow(row));
        // console.log(instance)
        console.log("hotTableRef.value.hotInstance", instance.getSourceDataAtRow(row));
    };



}



export class ProvideHotInstance {
    operation: Operation;
    hotInstance!: Handsontable;  // 使用 ! 声明属性
    hotInstanceSetting!: Handsontable.GridSettings;
    pagination: Pagination;
    hotElement: HTMLElement;
    hotElementInitSetting: HotElementInitSetting;


    constructor(hotElement: HTMLElement, hotElementInitSetting: HotElementInitSetting) {
        this.hotElement = hotElement;
        this.operation = new Operation();
        this.pagination = new Pagination();
        this.hotElementInitSetting = hotElementInitSetting;
        this.hotInstanceSetting = {
            data: [],
            colHeaders: [],
            colWidths: [],
            columns: []
        };
        this.init();

    }

    /**
     * 初始化数据
     */
    protected init(): void {
        console.log("初始化")
        this.initLanguage()
        this.initData()
        this.initColumns()
        this.initHeight()
        console.log(this.hotInstanceSetting)
        this.hotInstance = new Handsontable(this.hotElement, this.hotInstanceSetting);
    }

    /**
     * 初始化数据   
     */
    protected initData(): void {
        const columns = this.hotElementInitSetting.columns;
        const originData = this.hotElementInitSetting.data;

        if (!this.hotElementInitSetting.data || !this.hotElementInitSetting.columns) {
            this.hotInstanceSetting.data = [];
            return;
        }

        // 创建一个二维数组，第一行是列头，其他行是数据
        let formData: any[] = [];
        originData.map(ele => {
            return formData.push([]);
        });


        // 遍历props.data，将数据添加到formData中
        for (let i = 0; i < originData.length; i++) {
            columns.forEach(item => {
                formData[i].push(originData[i][item.key]);
            });
        }
        this.hotInstanceSetting.data = formData;
    }

    protected initHeight(): void {
        const originData = this.hotElementInitSetting.data;
        if (originData.length > 16) {
            this.hotInstanceSetting.height = "61vh";
        } else {
            this.hotInstanceSetting.height = "61vh";
        }
    }

    /**
     * 初始化Columns
     */
    protected initColumns(): void {
        const columns = this.hotElementInitSetting.columns;
        const originData = this.hotElementInitSetting.data;
        const operation = this.hotElementInitSetting.operation;
        // 明确指定类型
        this.hotInstanceSetting.colHeaders = [] as string[];
        this.hotInstanceSetting.colWidths = [] as number[];
        this.hotInstanceSetting.columns = [];



        for (let i = 0; i < columns.length; i++) {
            this.hotInstanceSetting.colHeaders.push(columns[i].title);
            this.hotInstanceSetting.colWidths.push(columns[i].width || 200);

            let col: { [key: string]: any } = {
                data: i,
                type: columns[i].type || 'text',
            }
            if (col.type === 'date' && !columns[i].dateFormat) {
                col.dateFormat = 'YYYY-MM-DD';
            }

            // 将props.columns[i]的属性添加到col中
            Object.assign(col, columns[i]);
            this.hotInstanceSetting.columns.push(col);
        }
        //添加操作列
        if (operation) {
            const enabledOperations = ['enableDelete', 'enableEdit', 'enableView']
                .filter(op => operation?.[op as keyof typeof operation] ?? false)
                .length;

            if (enabledOperations > 0) {
                const boundActionRenderer = this.actionRenderer.bind(this);
                this.hotInstanceSetting.columns.push({
                    title: '操作',
                    renderer: boundActionRenderer,
                    readOnly: true,
                    width: 50 * enabledOperations
                });
            }
            this.hotInstanceSetting.colWidths.push(enabledOperations * 50)
        }



        // 合并配置
        let settings: { [key: string]: any } = cloneDeep(defaultTableConfig);
        Object.assign(settings, this.hotInstanceSetting);
        this.hotInstanceSetting = settings;
    }




    /**
     * 初始化语言
     */
    protected initLanguage(): void {
        registerLanguageDictionary(zhCN);
        registerAllModules();
    }


    protected actionRenderer(
        instance: Core,
        td: HTMLTableCellElement,
        row: number,
        col: number,
        prop: number | string,
        value: object,
        cellProperties: CellProperties) {
        // console.log('实例类型:', instance?.constructor?.name, instance);
        // console.log('TD元素类型:', td?.constructor?.name, td);
        // console.log('行索引类型:', typeof row, row);
        // console.log('列索引类型:', typeof col, col);
        // console.log('属性类型:', typeof prop, prop);
        // console.log('值类型:', typeof value, value);
        // console.log('单元格属性类型:', cellProperties?.constructor?.name, cellProperties);

        td.innerHTML = '';
        td.className = 'action-column'; // 添加类名
        // 阻止容器的点击事件传播
        const container = document.createElement('div');
        container.className = 'action-container';
        container.addEventListener('mousedown', (e) => {
            e.stopPropagation();
        });
        const detailBtn = document.createElement('button');
        detailBtn.innerHTML = '详情';
        detailBtn.className = 'btn-detail';
        detailBtn.onmousedown = (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            e.preventDefault(); // 阻止默认行为
        };
        detailBtn.onclick = (e) => {
            e.stopPropagation();
            this.operation.handleDetail(this.hotInstance, row);
        };

        const deleteBtn = document.createElement('button');
        deleteBtn.innerHTML = '删除';
        deleteBtn.className = 'btn-delete';
        deleteBtn.onclick = (e) => {
            e.stopPropagation();
            this.operation.chandleDelete(this.hotInstance, row);
        };
        const editBtn = document.createElement('button');
        editBtn.innerHTML = '编辑';
        editBtn.className = 'btn-edit';
        editBtn.onclick = (e) => {
            e.stopPropagation();
            this.operation.chandleEdit(this.hotInstance, row);
        };

        td.appendChild(detailBtn);
        td.appendChild(deleteBtn);

        return td;
    };


    protected checkboxRenderer(instance: Core,
        td: HTMLTableCellElement,
        row: number,
        col: number,
        prop: number | string,
        value: object,
        cellProperties: CellProperties) {
    }


    /**
     * 获取父组件名称
     */
    public CallComponentName(): string {
        const instance = getCurrentInstance()
        const parentName = instance?.parent?.type?.name || "test";
        return parentName
    }
    /**
     * 获取hotInstance数据
     */
    getHotInstanceData(): Handsontable {
        return this.hotInstance;
    }

    /**
     * 获取hotInstance的配置信息
     */
    getHotInstanceSetting(): Operation {
        return this.operation;
    }


}
